""" 
Copyright 2009 Texas A&M University
 
Licensed under the Apache License, Version 2.0 (the "License"); you may not use 
this file except in compliance with the License. You may obtain a copy of the 
License at

http://www.apache.org/licenses/LICENSE-2.0
  
Unless required by applicable law or agreed to in writing, software distributed 
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
CONDITIONS OF ANY KIND, either express or implied. See the License for the 
specific language governing permissions and limitations under the License.
"""

from zope.component import adapts, queryUtility

from Products.GenericSetup.interfaces import ISetupEnviron
from Products.GenericSetup.utils import exportObjects
from Products.GenericSetup.utils import importObjects
from Products.GenericSetup.utils import XMLAdapterBase

from meercat.ui.plone.interfaces import IMeercatConnectionConfig


class MeercatConfigXMLAdapter(XMLAdapterBase):
    
    adapts(IMeercatConnectionConfig, ISetupEnviron)
    
    _LOGGER_ID = 'meercat.ui.plone'
    
    name = 'meercat'
    
    __parameter_types = ['default','forced']
    
    def _exportNode(self):
        """ export the object as a DOM node """
        node = self._doc.createElement('meercat')
        node.setAttribute('enabled',str(self.context.enabled))
        node.appendChild(self._exportSolrNode())
        node.appendChild(self._exportRestNode())
        self._logger.info('settings exported.')
        return node

    def _importNode(self, node):
        """ import the object from the DOM node """
        if self.environ.shouldPurge():
            self._purgeProperties()
        
        if node.hasAttribute('enabled'):
            self.context.enabled = self._convertToBoolean(node.getAttribute('enabled'))
        
        solrs = node.getElementsByTagName('solr')
        
        if solrs and len(solrs) > 0:
            if len(solrs) != 1:
                raise Exception(u'You must have at most 1 solr configuration')
            
            self._importSolrSettings(solrs[0])
        
        rests = node.getElementsByTagName('rest')
        
        if rests and len(rests) > 0:
            if len(rests) != 1:
                raise Exception(u'You must have at most 1 rest configuration')
            
            self._importRestSettings(rests[0])
        
        self._logger.info('settings imported.')
    
    def _importSolrSettings(self, node):
        if node.hasAttribute('enabled'):
            self.context.solr_enabled = self._convertToBoolean(node.getAttribute('enabled'))
        
        if node.hasAttribute('url'):
            self.context.solr_url = node.getAttribute('url')
        
        if node.hasAttribute('timeout'):
            self.context.solr_timeout = node.getAttribute('timeout')
        
        if node.hasAttribute('ssl_key_file'):
            self.context.solr_ssl_key_file = node.getAttribute('ssl_key_file')
        
        if node.hasAttribute('ssl_cert_file'):
            self.context.solr_ssl_cert_file = node.getAttribute('ssl_cert_file')
        
        for param in node.getElementsByTagName('parameter'):
            if not param.hasAttribute('type'):
                raise Exception(u'A parameter type must be specified')
            
            type = str(param.getAttribute('type')).lower()
            
            if not type in self.__parameter_types:
                raise Exception(u'Parameter type must be one of: %' % 
                                (', '.join(self.__parameter_types),))
            
            if not param.hasAttribute('name'):
                raise Exception(u'A parameter name must be specified')
            
            name = str(param.getAttribute('name'))
            
            values = getattr(self.context, 'solr_%s_parameters' % (type,))
            
            if param.hasAttribute('remove') and self._convertToBoolean(param.getAttribute('remove')):
                if name in values:
                    del values[name]
                continue
            
            value = self._getNodeText(param).strip()
            
            if value:
                values[name] = value
    
    def _importRestSettings(self, node):
        if node.hasAttribute('enabled'):
            self.context.rest_enabled = self._convertToBoolean(node.getAttribute('enabled'))
        
        if node.hasAttribute('url'):
            self.context.rest_url = node.getAttribute('url')
        
        if node.hasAttribute('timeout'):
            self.context.rest_timeout = node.getAttribute('timeout')
    
    def _purgeProperties(self):
        self.context.__init__()
    
    def _createNode(self, name, value):
        node = self._doc.createElement(name)
        node.setAttribute('value', value)
        return node

    def _exportSolrParameters(self, type):
        params = []
        for k,v in getattr(self.context,'solr_%s_parameters' % (str(type),)).iteritems():
            param = self._doc.createElement('parameter')
            param.setAttribute('type',str(type))
            param.setAttribute('name',str(k))
            param.appendChild(self._doc.createTextNode(v))
            params.append(param)
        return params
    
    def _exportSolrNode(self):
        node = self._doc.createElement('solr')
        node.setAttribute('enabled',str(self.context.solr_enabled))
        node.setAttribute('url',str(self.context.solr_url))
        node.setAttribute('timeout',str(self.context.solr_timeout))
        node.setAttribute('ssl_key_file',str(self.context.solr_ssl_key_file))
        node.setAttribute('ssl_cert_file',str(self.context.solr_ssl_cert_file))
        
        for type in self._parameter_types:
            for param in self._exportSolrParameters(type):
                node.appendChild(param)
        
        return node
    
    def _exportRestNode(self):
        node = self._doc.createElement('rest')
        node.setAttribute('enabled',str(self.context.rest_enabled))
        node.setAttribute('url',str(self.context.rest_url))
        node.setAttribute('timeout',str(self.context.rest_timeout))
        
        return node

def importMeercatSettings(context):
    """ import settings for meercat UI from an XML file """
    site = context.getSite()
    utility = queryUtility(IMeercatConnectionConfig, context=site)
    if utility is None:
        logger = context.getLogger('meercat.ui.plone')
        logger.info('Nothing to import.')
        return
    importObjects(utility, '', context)

def exportMeercatSettings(context):
    """ export settings for meercat UI as an XML file """
    site = context.getSite()
    utility = queryUtility(IMeercatConnectionConfig, context=site)
    if utility is None:
        logger = context.getLogger('meercat.ui.plone')
        logger.info('Nothing to export.')
        return
    exportObjects(utility, '', context)